<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>受控组件</title>
    <style>
        .list {
            width: 200px;
            height: 150px;
            background: skyblue;
            overflow: auto;
        }

        .news {
            height: 30px;
        }
    </style>
</head>
<body>
<div id="test"></div>
</body>
<script src="../js/new/react.development.js"></script>
<script src="../js/new/react-dom.development.js"></script>
<!--将jsx转为js-->
<script src="../js/new/babel.min.js"></script>
<script src="../js/new/prop-types.js"></script>
<!--babel  由babel转换jsx-->
<script type="text/babel">
    /*
    * 生命周期的三个阶段（新）
        1. 初始化阶段: 由ReactDOM.render()触发---初次渲染
            1.constructor()
            2.getDerivedStateFromProps
            3.render()
            4.componentDidMount()
        2. 更新阶段: 由组件内部this.setSate()或父组件重新render触发
            1.getDerivedStateFromProps
            2.shouldComponentUpdate()
            3.render()
            4.getSnapshotBeforeUpdate
            5.componentDidUpdate()
        3. 卸载组件: 由ReactDOM.unmountComponentAtNode()触发
            1.componentWillUnmount()
    * */
    class NewsList extends React.Component {

        state = {
            newsArr: []
        }

        componentDidMount() {
            setInterval(() => {
                const {newsArr} = this.state
                const news = '新闻' + (newsArr.length + 1)
                this.setState({
                    newsArr: [news, ...newsArr]
                })
            }, 1000)
        }

        // 获取更新前的数值，快照
        getSnapshotBeforeUpdate() {
            return this.refs.list.scrollHeight
        }

        //组件更新后
        componentDidUpdate(preProps, preState, snapshotValue) {
            this.refs.list.scrollTop += this.refs.list.scrollHeight - snapshotValue
        }

        render() {
            console.log('Sum-render')
            return (
                <div className="list" ref='list'>
                    {
                        this.state.newsArr.map((n, index) => {
                            return <div key={index} className="news">{n}</div>
                        })
                    }
                </div>
            )
        }
    }

    ReactDOM.render(<NewsList/>, document.getElementById('test'))
</script>
</html>